package com.my.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.my.util.ApiUtil;

import java.util.Date;

public class NightSpotService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        SharedPreferences preferences = getApplicationContext().getSharedPreferences("LOGIN_DATA", Context.MODE_PRIVATE);
        JSONObject setting = JSONUtil.parseObj(preferences.getString("setting", null));
        new Thread(() -> {
            DateTime dateTime = DateUtil.offsetMinute(DateUtil.parse(DateUtil.format(new Date(), "yyyy-MM-dd ") + setting.getStr("nightSpotStartTime"), "yyyy-MM-dd HH:mm"), -11);
            while (!DateUtil.format(dateTime, "yyyy-MM-dd HH:mm").equals(DateUtil.format(new DateTime(), "yyyy-MM-dd HH:mm"))) {
                try {
                    Thread.sleep(1000 * 60);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dateTime = DateUtil.offsetMinute(DateUtil.parse(DateUtil.format(new Date(), "yyyy-MM-dd ") + setting.getStr("nightSpotStartTime"), "yyyy-MM-dd HH:mm"), -11);
            }
            try {
                Thread.sleep(1000 * 60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Intent i = new Intent(NightSpotService.this, NightSpotReceiver.class);
            PendingIntent pi = PendingIntent.getBroadcast(NightSpotService.this, 0, i, 0);
            manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent i = new Intent(this, NightSpotReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.cancel(pi);
    }
}
